package cn.likecy.sqlapp;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.simple.SimpleDataSource;
import cn.likecy.sqlapp.domain.PhotoMini;

import javax.sql.DataSource;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static cn.likecy.sqlapp.util.ImgUtil.GenImageByObjToFilePath;


public class WindowShowRunner extends JFrame {


    protected String baseSaveDir ="";

    private String sqlServerJdbcUrl ="";

    private String sqlServeruserNameValText ="";

    private String sqlServerpassWordValText ="";
    protected boolean isWork = false;

    public WindowShowRunner() {

        // 执行任务线程
        ExecutorService pool = Executors.newCachedThreadPool();

        setTitle("SqlServer读取图片保存小程序");

        //设置窗口的大小
        setSize(400,680);

        //设置窗口显示位置
        setLocation(500,200);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        //获取容器
        Container c = getContentPane();
        //设置布局
        FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 20, 30);
        c.setLayout(flowLayout);

        //创建标签
        JLabel sqlServerHost = new JLabel("主机IP:");

        //设定文本框长度
        JTextField sqlServerHostVal = new JTextField(20);

        JLabel sqlServerPort = new JLabel("主机端口:");
        //设定文本框长度
        JTextField sqlServerPortVal = new JTextField(20);
        JLabel databaseName = new JLabel("数据库名称:");

        //设定文本框长度
        JTextField databaseNameVal = new JTextField(20);

        JLabel userName = new JLabel("数据库账户名:");

        //设定文本框长度
        JTextField userNameVal = new JTextField(20);

        JLabel passWord = new JLabel("数据库连接密码:");
        //设定文本框长度
        JTextField passWordVal = new JTextField(20);


        JLabel info = new JLabel("操作记录：");
        JTextArea infoVal = new JTextArea();
        infoVal.setRows(10);
        infoVal.setColumns(28);

        //确定输入按钮
        JButton btninput = new JButton("开始");


        // 任务执行主体
        Runnable rn = () -> {
            infoVal.append("连接地址:   "+sqlServerJdbcUrl+"\n");
            infoVal.append("正在连接请等待....\n");
            //获取sqlserver 链接
            DataSource ds = new SimpleDataSource(sqlServerJdbcUrl, sqlServeruserNameValText, sqlServerpassWordValText);
            try {
                // 测试数据库连接是否成功
                Connection connection = ds.getConnection();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(c,ex.getMessage(),"数据库连接错误",JOptionPane.ERROR_MESSAGE);
                isWork = false;
                btninput.setEnabled(true);
                infoVal.append("数据库连接错误!\n");
                return;
            }
            infoVal.append("连接成功!\n");
            // 查询数量
            String selectCountSql ="SELECT count(*) as count_num from Photo";
            List<Entity> queryCountList = null;
            try {
                queryCountList = Db.use(ds).query(selectCountSql);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(c,ex.getMessage(),"数据库查询Photo表错误",JOptionPane.ERROR_MESSAGE);
                isWork = false;
                btninput.setEnabled(true);
                return;
            }
            String showMsg = "数据库共有"+queryCountList.get(0).get("count_num")+"条记录 \n";
            infoVal.append(showMsg);
            infoVal.append("正在检索信息...请等待");
            System.out.println(showMsg);
            // 查询sql语句
            String selectSql ="";
            selectSql = "SELECT * from Photo";
            // 发起请求并获取记录
            List<Entity> queryList = null;
            try {
                queryList = Db.use(ds).query(selectSql);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(c,ex.getMessage(),"数据库查询Photo表错误",JOptionPane.ERROR_MESSAGE);
                isWork = false;
                btninput.setEnabled(true);
                return;
            }
            Long count =0L;
            if(queryList.size()==0){
                JOptionPane.showMessageDialog(c,"此数据库暂无数据","数据库查询Photo表错误",JOptionPane.ERROR_MESSAGE);
                isWork = false;
                btninput.setEnabled(true);
                return;
            }
            for (Entity entity : queryList) {
                // 查询map转Bean
                PhotoMini photo = entity.toBean(PhotoMini.class);
                count++;
                infoVal.append("正在解析第"+count+"张图片 \n");
                // 照片对象bite[]保存为图片到相应文件夹
                GenImageByObjToFilePath(photo,baseSaveDir);
            }
            infoVal.append("完成所有转换!\n");
            isWork = false;
            btninput.setEnabled(true);
            JOptionPane.showMessageDialog(c,"完成所有转换!","完成提示",JOptionPane.INFORMATION_MESSAGE);
        };





        JLabel btnChooseFileVal = new JLabel();
        JButton btnChooseFile = new JButton("选择保存路径");
        btnChooseFile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int option = fileChooser.showOpenDialog(c);
                if(option == JFileChooser.APPROVE_OPTION){
                    File file = fileChooser.getSelectedFile();
                    btnChooseFileVal.setText("选择了: " + file.getAbsolutePath());
                    baseSaveDir = file.getAbsolutePath();
                }
            }
        });


        btninput.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if (isWork){
                    JOptionPane.showMessageDialog(c,"请勿重复提交运行任务！","运行提示",JOptionPane.ERROR_MESSAGE);
                    return;
                }

                String sqlServerHostValText = sqlServerHostVal.getText();
                if(sqlServerHostValText.equals("")){
                    JOptionPane.showMessageDialog(c,"服务器IP未填写","填写错误",JOptionPane.ERROR_MESSAGE);
                    return;
                }
                String sqlServerPortValText = sqlServerPortVal.getText();
                if(sqlServerPortValText.equals("")){
                    JOptionPane.showMessageDialog(c,"服务器端口未填写","填写错误",JOptionPane.ERROR_MESSAGE);
                    return;
                }
                String databaseNameValText =  databaseNameVal.getText();
                if (databaseNameValText.equals("")){
                    JOptionPane.showMessageDialog(c,"数据库名称未填写","填写错误",JOptionPane.ERROR_MESSAGE);
                    return;
                }

                String userNameValText =  userNameVal.getText();
                if(userNameValText.equals("")){
                    JOptionPane.showMessageDialog(c,"数据库用户名未填写","填写错误",JOptionPane.ERROR_MESSAGE);
                    return;
                }
                String passWordValText =  passWordVal.getText();
                if(passWordValText.equals("")){
                    JOptionPane.showMessageDialog(c,"数据库密码未填写","填写错误",JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if(baseSaveDir.equals("")){
                    JOptionPane.showMessageDialog(c,"未选择保存文件夹","填写错误",JOptionPane.ERROR_MESSAGE);
                    return;
                }

                isWork = true;
                btninput.setEnabled(false);
                // 复制操作   构造jdbc地址
                sqlServerJdbcUrl = "jdbc:sqlserver://"+sqlServerHostValText+":"+sqlServerPortValText+";DatabaseName="+databaseNameValText;;
                sqlServeruserNameValText = userNameValText;
                sqlServerpassWordValText = passWordValText;
                // 启动线程
                pool.execute(rn);

            }
        });

        //退出按钮
        JButton btnclose = new JButton("退出");
        //对退出按钮设置监听
        btnclose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });


        Panel sqlServerHostPanel = new Panel();
        sqlServerHostPanel.add(sqlServerHost);
        sqlServerHostPanel.add(sqlServerHostVal);
        c.add(sqlServerHostPanel);


        Panel sqlServerPortpanel = new Panel();
        sqlServerPortpanel.add(sqlServerPort);
        sqlServerPortpanel.add(sqlServerPortVal);
        c.add(sqlServerPortpanel);


        Panel databaseNamePanel = new Panel();
        databaseNamePanel.add(databaseName);
        databaseNamePanel.add(databaseNameVal);
        c.add(databaseNamePanel);

        Panel userNamePanel = new Panel();
        userNamePanel.add(userName);
        userNamePanel.add(userNameVal);
        c.add(userNamePanel);

        Panel passWordPanel = new Panel();
        passWordPanel.add(passWord);
        passWordPanel.add(passWordVal);
        c.add(passWordPanel);

        Panel btnChooseFilePanel = new Panel();
        btnChooseFilePanel.add(btnChooseFileVal);
        c.add(btnChooseFilePanel);



        Panel btnInputPanel = new Panel();
        btnInputPanel.add(btnChooseFile);
        btnInputPanel.add(btninput);
        btnInputPanel.add(btnclose);
        c.add(btnInputPanel);

        JScrollPane jscrollInfoView=new JScrollPane(infoVal);
        //分别设置水平和垂直滚动条自动出现
        jscrollInfoView.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        jscrollInfoView.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        c.add(info);
        c.add(jscrollInfoView);

        //设置可见
        setVisible(true);
    }

    public static void main(String[] args) {
        new WindowShowRunner();
    }

}


